package controller;

import java.io.Serializable;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.HashMap;

import DAO.DatabasePool;
import DAO.FTRelationTimeDAO;


import model.ConnectionProperty;
import model.FTRelationTime;
import rdbms.RDBMSFTConceptTimeDAO;
import rdbms.RDBMSFTRelationTimeDAO;

public class Job implements Serializable {

	private static final long serialVersionUID = 1L;
	HashMap<String, Term> map = null;
	Term source;
	int date;

	Job(Term source, Object object, int date) {
		this.map = (HashMap<String, Term>) object;
		this.source = source;
		this.date = date;
	}

	public HashMap<String, Term> getMap() {
		return map;
	}

	public int getDate() {
		return date;
	}

	public Term getSource() {
		return source;
	}

	public void setSource(Term source) {
		this.source = source;
	}

	public void execute() throws Exception {
		System.out.println("Tamanho " + map.size());
		Search search = new Search();
		DecimalFormat decimal = new DecimalFormat( "0.000000000000" );

			ConnectionProperty conn;
			String dbId = "";
			String jobId = "FTRelationTime";
			String connectionId = "1";

			conn = new ConnectionProperty(jobId, connectionId,
					TestUtil.Drivers.POSTGRE.getDriver(),
					TestUtil.Drivers.POSTGRE.getUrl(),
					TestUtil.Drivers.POSTGRE.getUser(),
					TestUtil.Drivers.POSTGRE.getPassword(),
					TestUtil.Drivers.POSTGRE.getSchema());
			DatabasePool.create(conn);

			dbId = conn.getId();

			RDBMSFTRelationTimeDAO rtDAO = new RDBMSFTRelationTimeDAO(dbId);
			
			double d = 5000000000L;
			
			for (String key : map.keySet()) {
				int a = search.generateFrequency(source.getDescription(), map.get(key).getDescription());
				int b = map.get(key).getFrequency();
				int c = source.getFrequency();
				d = d-(a+b+c);
				rtDAO.insert(new FTRelationTime(source.getId(), map.get(key).getId(), 1, 1,Double.parseDouble(decimal.format(this.phiSquare(a, b, c, d))), 0, a));
				System.out.println("a ="+a+" b = "+b+" c ="+c+" d = "+d);
		}
		// persistir.

	}

	public double phiSquare(final double a, final double b,
			final double c, final double d) throws Exception {
		return (Math.pow((a * d) - (b * c), 2.0))
				/ ((a + b) * (a + c) * (b + d) * (c + d));
	}

}
